import XLSX from 'xlsx';

import math from './math';

const addZero = item => {
  item = item < 10 ? '0' + item : item;
  return item;
};

/**
 * 时间格式化
 * @param {*} date 时间
 * @param {*} type 格式
 * @param {*} spilitLet 分隔符
 */
const dateFormat = (date, type = 'yyyy-MM-dd', spilitLet = '-') => {
  // console.log('date util',date);
  let newdate = date.replace ? date.replace(/-/g, '/') : date;
  const _date = new Date(newdate);
  let year = _date.getFullYear(),
    month = addZero(_date.getMonth() + 1),
    day = addZero(_date.getDate()),
    hour = addZero(_date.getHours()),
    minute = addZero(_date.getMinutes()),
    second = addZero(_date.getSeconds()),
    result = '';

  switch (type) {
    case 'yyyy':
      result = year + '';
      break;
    case 'yyyy-MM':
      result = year + spilitLet + month;
      break;
    case 'yyyy-MM-dd':
      result = year + spilitLet + month + spilitLet + day;
      break;
    case 'yyyy-MM-dd HH':
      result = year + spilitLet + month + spilitLet + day + ' ' + hour;
      break;
    case 'yyyy-MM-dd HH:mm':
      result = year + spilitLet + month + spilitLet + day + ' ' + hour + ':' + minute;
      break;
    case 'yyyy-MM-dd HH:mm:ss':
      result = year + spilitLet + month + spilitLet + day + ' ' + hour + ':' + minute + ':' + second;
      break;
  }
  return result;
};

/**
 * 去抖动
 * @param {*} fn
 * @param {*} delay
 */
const debounce = (fn, delay) => {
  let timeoutID = null;
  // eslint-disable-next-line func-names
  return function() {
    let context = this;
    clearTimeout(timeoutID);
    timeoutID = setTimeout(() => {
      fn.apply(context, arguments);
    }, delay);
  };
};

/**
 * 节流函数
 * @param {*} fn
 * @param {*} wait
 */
const throttle = (fn, wait) => {
  let previous = 0;
  // eslint-disable-next-line func-names
  return function() {
    let now = new Date().getTime();
    if (now - previous > wait) {
      fn.apply(this, arguments);
      previous = now;
    }
  };
};

/**
 *格式化数量
 */
const formatNum = (num, digs = 2) => {
  if (isNaN(num)) {
    return 0;
  }

  // return num.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const k = 10000;
  const sizes = ['', '万', '亿', '万亿'];
  // console.log('num', num);
  if (num < k) {
    return Number(num);
  }
  const i = Math.floor(Math.log(num) / Math.log(k));
  if (i === 0) {
    return num.toFixed(0);
  }
  // console.log((num / Math.pow(k, i)).toFixed(digs) + sizes[i]);
  return (num / Math.pow(k, i)).toFixed(digs) + sizes[i];
};
/**
 * 数字加逗号分隔
 * @param {*} money
 */
const formatNumNormal = num => {
  if (!num) {
    return '-';
  }
  if (isNaN(num)) {
    return 0;
  }

  return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
/**
 * 格式化金钱
 * @param {*} money
 */
const formatMoney = money => {
  if (isNaN(money)) {
    return 0;
  }
  const k = 10000;
  const sizes = ['', '万', '亿', '万亿'];
  if (money < k) {
    return money;
  }
  const i = Math.floor(Math.log(money) / Math.log(k));
  return (money / Math.pow(k, i)).toFixed(2) + sizes[i];
};
/**
 * 文件大小格式化
 * @param {*} value
 */
const formatFileSize = value => {
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  let index = 0,
    srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  let size = srcsize / Math.pow(1024, index);
  size = size.toFixed(2); // 保留的小数位数
  return size + unitArr[index];
};

/**
 * 转义html
 * @param {*} html
 */
const encodeHtml = html => {
  if (html && html.replace) {
    return html
      .replace(/&/g, '&amp;') // 转换&符号
      .replace(/ /g, '&nbsp;') // 转换空格
      .replace(/\b&nbsp;+/g, ' ') // 转换多个空格为单个空格
      .replace(/</g, '&lt;') // 转换小于符号
      .replace(/>/g, '&gt;') // 转换大于符号
      .replace(/\\/g, '&#92;') // 转换斜杠符号
      .replace(/\'/g, '&#39;') // 转换单引号
      .replace(/\"/g, '&quot;') // 转换双引号
      .replace(/\n/g, '<br/>') // 转换换行符号
      .replace(/\r/g, ''); // 转换回车符号
  }
  return html;
};

/**
 * 深度拷贝
 * @param {*} data 数据
 */
const deepCopy = data => {
  let copyed_objs = []; // 此数组解决了循环引用和相同引用的问题，它存放已经递归到的目标对象
  function _deepCopy(target) {
    if (typeof target !== 'object' || !target) {
      return target;
    }
    for (let i = 0; i < copyed_objs.length; i++) {
      if (copyed_objs[i].target === target) {
        return copyed_objs[i].copyTarget;
      }
    }
    let obj = {};
    if (Array.isArray(target)) {
      obj = []; // 处理target是数组的情况
    }
    copyed_objs.push({ target, copyTarget: obj });
    Object.keys(target).forEach(key => {
      if (obj[key]) {
        return;
      }
      obj[key] = _deepCopy(target[key]);
    });
    return obj;
  }
  return _deepCopy(data);
};

/**
 * 对象转数组
 * @param {*} keys 转化的key
 * @param {*} data 对象数组
 */
const jsonToArray = (keys, data) => data.map(item => keys.map(key => (key === 'date' && item[key].length < 8 ? item[key].replace(/-/g, '') : item[key])));

/**
 * excel下载
 * @param {*} headers 对象数组|{prop:'',label:''}
 * @param {*} data 对象数组
 * @param {*} fileName 文件名
 * @param {*} fileType 文件类型
 */
const download = (headers, data, fileName = '下载文件', fileType = 'csv') => {
  console.log('headers', headers);
  const keys = headers.map(item => item.prop);

  const headerText = headers.map(item => {
    if (item.label && item.label.includes && item.label.includes('万元')) {
      return item.label.slice(0, item.label.length - 4);
    }
    return item.label;
  });

  // console.log('keys', keys);
  // console.log('headerText', headerText);

  // const arr = data.length > 0 ? jsonToArray(keys, data) : [];
  const arr = jsonToArray(keys, data);
  // console.log(XLSX);

  const ws = XLSX.utils.aoa_to_sheet([headerText, ...arr]);

  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, fileName + '.' + fileType);
};

/**
 * loadScript
 * @param {*} path
 * @param {*} callback
 */
const loadScript = (path, callback) => {
  let done = false,
    scr = document.createElement('script');

  scr.onload = handleLoad;
  scr.onreadystatechange = handleReadyStateChange;
  scr.onerror = handleError;
  scr.src = path;
  document.body.appendChild(scr);

  function handleLoad() {
    if (!done) {
      done = true;
      callback(path, 'ok');
    }
  }

  function handleReadyStateChange() {
    let state;

    if (!done) {
      state = scr.readyState;
      if (state === 'complete') {
        handleLoad();
      }
    }
  }
  function handleError() {
    if (!done) {
      done = true;
      callback(path, 'error');
    }
  }
};

const randomItem = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);

const getUUID = () => randomItem() + randomItem() + '-' + randomItem() + '-' + randomItem() + '-' + randomItem() + '-' + randomItem() + randomItem() + randomItem();

const sortDashBoard = (data, key) => {
  let totalItem = data.filter(item => item[key] === '总'),
    others = data.filter(item => item[key] !== '总');
  others = others.sort((a, b) => String(a[key]).localeCompare(b[key], 'zh-CN'));
  return totalItem.concat(others);
};

/**
 * 万元定位
 * @param {*} value
 */
const thousand = value => {
  if (!value || isNaN(value)) {
    return 0;
  }

  if (Number(value) === 0) {
    return 0;
  }
  if (Number(value) < 1000) {
    return math.divide(value, 10000, 4);
  }
  const tnum = math.divide(value, 10000, 2);
  return formatNumNormal(tnum);
};

/**
 * 类目解析
 * @param {*} value
 */
const categoryName = value => {
  if (value && value.includes && value.includes('--')) {
    const arr = value.split('--');
    if (arr.length > 2) {
      return arr.slice(2).join('--');
    }
    return arr[arr.length - 1];
  }
  return value;
};

/**
 * 数组里是否包含
 * @param {*} array
 * @param {*} b
 */
const isContainer = (array, b) => {
  // 数组
  if (b instanceof Array) {
    return b.every(item => array.includes(item));
  }
  if (array.includes(b)) {
    return true;
  }
  return false;
};

/**
 * 逗号分割数值
 * @param {*} num
 */
const toThousandFilter = num => {
  if (typeof num === 'undefined') {
    return '--';
  }
  if (isNaN(num)) {
    return 0;
  }
  return (num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','));
};

/**
 * w 格式化
 */
const tenThousand = value => {
  if (typeof value === 'undefined') {
    return '--';
  }
  if (isNaN(value)) {
    return 0;
  }
  if (Number(value) < 10000) {
    return value;
  }
  const tnum = math.divide(value, 10000, 2);
  return toThousandFilter(tnum) + 'w';
};

// const logData = value => {
//   if (navigator.sendBeacon) {
//     navigator.sendBeacon('/log', analyticsData);
//   } else {
//     const client = new XMLHttpRequest();
//     client.open('POST', '/log', false); // 第三个参数表明是同步的 xhr
//     client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
//     client.send(analyticsData);
//   }
// };

export default {
  addZero,
  dateFormat,
  formatNum,
  formatNumNormal,
  formatMoney,
  debounce,
  throttle,
  encodeHtml,
  deepCopy,
  download,
  jsonToArray,
  loadScript,
  getUUID,
  formatFileSize,
  sortDashBoard,
  thousand,
  categoryName,
  isContainer,
  tenThousand,
  toThousandFilter
};
